package app

import android.Manifest
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import com.hontech.pastadebug.service.KeepAliveService
import ext.log
import manager.AppManager
import manager.AppTask

private lateinit var INSTANCE: Application

class App : Application(), Thread.UncaughtExceptionHandler, Runnable {

    companion object {
        const val PROCESS = "com.hontech.pizza"
    }

    //private val delegate = AppDelegate(this)

    override fun uncaughtException(t: Thread?, e: Throwable?) {
        if (e != null) {
            e.printStackTrace()
        } else {
            log("未知异常")
        }
        AppManager.resetApp()
    }

    override fun onCreate() {
        super.onCreate()
        val name = processName()
        if (name != PROCESS) {
            return
        }
        INSTANCE = this
        Thread.setDefaultUncaughtExceptionHandler(this)
        AppTask.post(this)
        log(name, "进程名称")
        checkPermission()
        AppManager.initApp()
    }

    private fun checkPermission() {
        val v = AppManager.checkAndGrantPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        log("读权限:$v")
        val v1 = AppManager.checkAndGrantPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        log("写权限:$v1")
    }

    private fun processName(): String {
        val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningApps = am.getRunningAppProcesses()
        for (proInfo in runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                return proInfo.processName
            }
        }
        return ""
    }

    override fun run() {
        KeepAliveService.mainProcessTimerCallback(this)
        AppTask.postDelayed(this, 5 * 1000)
    }
}

object AppContext : ContextWrapper(INSTANCE)
